import React from 'react';
import PropTypes from 'prop-types';
import _ from 'lodash';
import moment from 'moment';
import {
  TASK_PRIORITY_MAP,
  TASK_PROTOCOL_MAP,
  TASK_TYPE_MAP,
  TIME_UNIT_MAP
} from '@util/constants';
import TargetCard from '@containers/task-manage/components/TargetCard';
import getRealTime from '@util/get-real-time';
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';
import './index.less';

const TaskInfo = props => {
  const { task, defaultInterface, nodeRole } = props,
    scanType = _.get(task, 'scanType'),
    taskTypeName = ['Web', 'Honeypot'].includes(scanType)
      ? '资产探测任务'
      : TASK_TYPE_MAP[scanType],
    taskParams = _.get(task, 'maxDetectionTaskParams', {}),
    taskTargets = [];
  if (
    ['custom', 'siteIdList', ' affectedByTarget', 'targetGroup'].includes(
      _.get(taskParams, 'target.queryType')
    )
  ) {
    if (_.get(taskParams, 'target.showList.length')) {
      taskTargets.push(..._.get(taskParams, 'target.showList', []));
    }
  } else if (_.get(taskParams, 'target.count') !== 0) {
    taskTargets.push(_.get(taskParams, 'target.description'));
  }

  const timing = _.get(task, 'timing', {});
  let predictNextStartAt = '-';
  let lastStartTIme = '-';
  let detectionTime = '-';
  lastStartTIme = _.get(task, 'lastStart');
  const status = _.get(task, 'status');
  const pendingTime = _.get(task, 'pendingTime', '');

  const lastEnd = _.get(task, 'lastEnd');
  const recentEndTime =
    !['processing', 'paused', 'stopped'].includes(status) && _.get(task, 'lastEnd');
  if (status === 'finished') {
    detectionTime = getRealTime(lastStartTIme, lastEnd, pendingTime, 'done');
  }
  if (_.get(task, 'isCycle')) {
    const lastEnd = _.get(task, 'lastEnd');
    const interval = _.get(task, 'intervalTime');
    const unit = `${_.get(task, 'intervalUnit')}`;
    const status = _.get(task, 'status');
    const endAt = _.get(timing, 'endAt');
    const dailyEnd = _.get(timing, 'dailyEnd');
    const dailyStart = _.get(timing, 'dailyStart');
    const intervalTime = moment(lastEnd)
      .add(interval, unit)
      .format('YYYY-MM-DD HH:mm:ss');
    const isBetween = (dailyStart, dailyEnd, intervalTime) => {
      let dailyStartDate = new Date(moment(intervalTime));
      dailyStartDate.setHours(dailyStart.split(':')[0]);
      dailyStartDate.setMinutes(dailyStart.split(':')[1]);
      let dailyEndDate = new Date(moment(intervalTime));
      dailyEndDate.setHours(dailyEnd.split(':')[0]);
      dailyEndDate.setMinutes(dailyEnd.split(':')[1]);
      if (
        moment(moment(intervalTime).format('YYYY-MM-DD HH:mm')).isBetween(
          moment(dailyStartDate).format('YYYY-MM-DD HH:mm'),
          moment(dailyEndDate).format('YYYY-MM-DD HH:mm')
        )
      ) {
        return true;
      }
      return false;
    };
    const InspectionTime = () => {
      if (endAt || dailyEnd) {
        if (intervalTime < moment(endAt).format('YYYY-MM-DD HH:mm:ss')) {
          if (dailyStart && dailyEnd) {
            return isBetween(dailyStart, dailyEnd, intervalTime);
          }
          return true;
        }
        if (dailyStart && dailyEnd) {
          return isBetween(dailyStart, dailyEnd, intervalTime);
        }
        return false;
      }
      return true;
    };
    if (
      lastEnd &&
      interval &&
      unit &&
      recentEndTime &&
      !['paused', 'stopped'].includes(status) &&
      InspectionTime()
    ) {
      predictNextStartAt = moment(lastEnd)
        .add(interval, unit)
        .format('YYYY-MM-DD HH:mm:ss');
    }
  }

  const interfaces = _.get(taskParams, 'interface', 'any');
  let connectionCount = _.get(taskParams, 'connectionCount');
  if (connectionCount === 0) {
    connectionCount = '不限制';
  }

  const timingStartAndEnd =
    _.get(timing, 'startAt') && _.get(timing, 'endAt')
      ? `${_.get(timing, 'startAt')} 至 ${_.get(timing, 'endAt')}`
      : _.get(timing, 'startAt')
      ? `任务须在${_.get(timing, 'startAt')}以后开始`
      : _.get(timing, 'endAt')
      ? `任务须在${_.get(timing, 'endAt')}以前结束`
      : '不限制';
  let details = [
    ['忽略网络打印机端口', _.get(taskParams, 'ignorePrinterPortCheck', false) ? '是' : '否'],
    [
      '禁扫目标',
      _.get(task, 'ignoreType', []).includes('whiteList') ? (
        <span>
          启用&nbsp;&nbsp;&nbsp;&nbsp;<Link to={'/asset-config/white-list'}>查看详情</Link>
        </span>
      ) : (
        '禁用'
      )
    ],
    ['仅端口探活', _.get(taskParams, 'portDetectionOnly', false) ? '是' : '否'],
    ['Web指纹探测', _.get(taskParams, 'webFingerprintDetection', false) ? '是' : '否'],
    ['操作系统深度探测', _.get(taskParams, 'depthDetect', true) ? '是' : '否'],
    [
      '协议类型',
      _.get(taskParams, 'protocol', [])
        .map(protocol => TASK_PROTOCOL_MAP[protocol])
        .filter(Boolean)
        .join('、') || '-'
    ],
    ['国产化识别', '系统软件、数据库、操作系统、硬件设备'],
    ['最大连接并发数', `${connectionCount ? connectionCount : '-'}`],
    [
      '扫描带宽',
      _.get(taskParams, 'speedLimit') ? `${_.get(taskParams, 'speedLimit')}Kbps` : '无限制'
    ],
    [
      '任务类型',
      _.get(task, 'isCycle')
        ? `周期(${_.get(task, 'intervalTime')}${TIME_UNIT_MAP[_.get(task, 'intervalUnit')]})`
        : '单次'
    ],
    ['定时设置', timingStartAndEnd],
    [
      '每日允许时间段',
      _.get(timing, 'dailyStart') && _.get(timing, 'dailyEnd')
        ? `${_.get(timing, 'dailyStart')} 至 ${_.get(timing, 'dailyEnd')}`
        : '-'
    ],
    ['扫描网口', interfaces === defaultInterface ? '默认' : `${interfaces}`],
    ['优先级', TASK_PRIORITY_MAP[_.get(task, 'priority')] || '-'],
    [<div key="repeat">探测轮次</div>, `${_.get(task, 'times', 1) || '1'}次`],
    ['最近一轮开始时间', lastStartTIme],
    ['最近一轮结束时间', recentEndTime || '-'],
    ['最近一轮检测耗时', detectionTime],
    ['预计下轮开始时间', predictNextStartAt]
  ].filter(Boolean);
  // eslint-disable-next-line react/prop-types
  if (nodeRole !== 'single') {
    details.splice(12, 1);
  }
  return (
    <div className="task-info">
      <div className="task-name">
        <span className="name">{_.get(task, 'name', '-')}</span>
        <span className="type">{taskTypeName ? `${taskTypeName}任务` : '-'}</span>
      </div>
      <div className="task-info-detail">
        <div className="task-info-left">
          <TargetCard
            name={`探测目标 (${_.get(taskParams, 'target.count', '-')}) 个`}
            items={taskTargets}
            moreItems={taskTargets}
            type="target"
          />
          <TargetCard
            name={`探测端口 (${_.get(taskParams, 'portCount', '-')}) 个`}
            items={_.get(taskParams, 'ports', 0)}
            moreItems={_.get(taskParams, 'ports', 0)}
            type="port"
          />
          {details.slice(0, 6).map((detail, index) => {
            return (
              <div className="detail-item" key={index}>
                <span className="name">{detail[0]}</span>
                <span className="value">{detail[1]}</span>
              </div>
            );
          })}
        </div>
        <div className="task-info-right">
          {details.slice(6).map((detail, index) => {
            return (
              <div className="detail-item" key={index}>
                <span className="name">{detail[0]}</span>
                <span className="value">{detail[1]}</span>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
};

const mapStateToProps = state => {
  return {
    nodeRole: _.get(state, 'auth.cert.nodeRole', 'single')
  };
};

TaskInfo.propTypes = {
  task: PropTypes.object,
  defaultInterface: PropTypes.string,
  nodeRole: PropTypes.string
};

export default connect(mapStateToProps)(TaskInfo);
